package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.AdvertisementOrder;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.AdvertisementOrderService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 广告 订单 详情页面
 */
public class AdvertisementOrderDetailActivity extends BaseActivity {
    private static final String TAG = "RechargeDetailActivity";

    public static void startActivity(Context context, String advertisementOrderId) {
        context.startActivity(new Intent(context, AdvertisementOrderDetailActivity.class).putExtra("advertisementOrderId", advertisementOrderId));
    }

    public static void startActivity(Context context, AdvertisementOrder advertisementOrder) {
        context.startActivity(new Intent(context, AdvertisementOrderDetailActivity.class).putExtra("advertisementOrder", advertisementOrder));
    }

    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_amount_tips)
    TextView tv_amountTips;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_id)
    TextView tv_Id;
    @BindView(R.id.tv_created)
    TextView tv_created;
    @BindView(R.id.tv_show_advertisement)
    TextView tv_showAdvertisement;

    @BindView(R.id.tv_customer_service)
    TextView tv_customerService;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;


    private String advertisementOrderId;
    private AdvertisementOrder order;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertisement_order_detail);
        ButterKnife.bind(this);
        advertisementOrderId = getIntent().getStringExtra("advertisementOrderId");
        order = getIntent().getParcelableExtra("advertisementOrder");
        if (order != null) {
            advertisementOrderId = order.getId();
            setupViews(order);
        } else {
            loadData();
        }
        tv_customerService.setOnClickListener(v -> contactCustomerService());

    }


    private void loadData() {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AdvertisementOrderService.class)
                .getOrder(advertisementOrderId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        Object data = body.getData();
                        if (data != null) {
                            JSONObject jsonObject = (JSONObject) data;
                             order = jsonObject.toJavaObject(AdvertisementOrder.class);
                            setupViews(order);

                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                    }
                });
    }

    private void setupViews(AdvertisementOrder order) {
        tv_amount.setText(Utils.moneyFormat(order.getAmount()));
        tv_amountTips.setText("交易成功");
        tv_title.setText(order.getTitle());
        String durationTime = DateUtils.computeDurationTime(order.getStartDate(), order.getEndDate());
        tv_time.setText(durationTime);
        tv_Id.setText(order.getId());
        tv_created.setText(DateUtils.dateToString(order.getStartDate(), DateUtils.FORMAT_TIMESTAMP));
        tv_showAdvertisement.setOnClickListener(v -> toAdvertisementDetail());
    }


    /**
     * 进入广告详情页面
     */
    private void toAdvertisementDetail() {
        AdvertisementDetailActivity.startActivity(this, order.getaId());
    }

    /**
     * 联系客服
     */
    private void contactCustomerService() {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        ChatActivity.startActivity(AdvertisementOrderDetailActivity.this, manualUser);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }

}